import { useState } from "react";
import {useWebscoket} from '../../hooks/useWebscoket'
import '../../Page/style.css'

let wss = null;
const App = () => {
  const user_id = "1";
  const server_id = "1";
  const [value, setValue] = useState("");
  const [list, setList] = useState([]);
  useWebscoket({ user_id, server_id }, (ws) => {
    ws.send(
      JSON.stringify({
        type: "getChatList",
      })
    );

    ws.onmessage = (e) => {
      const { type, message, data } = JSON.parse(e.data);
      console.log(type, data);
      if (type === "getChatList") {
        setList(data);
        console.log("聊天记录", data);
      }

      if (type === "addMessage") {
        setList((prev) => {
          console.log("聊天记录", [...prev, data]);
          return [...prev, data];
        });
      }
    };

    wss = ws;
  });


  const handleSend = () => {
    wss.send(
      JSON.stringify({
        type: "addMessage",
        data: {
          user_id,
          server_id,
          message: value,
        },
      })
    );
  };

  const handleChoose = () => {
    const input = document.createElement('input')
    input.type = 'file'
    input.click()

    input.onchange = e => {
      const file = e.target.files[0];
      console.log(file)
    }
  }

  return (
    <div>
      <div className="header">聊天</div>
      <div className="content">
        {list.map((v, i) => {
          const myClassName = v.dir === 1 ? 'content-right': 'content-left'
          const avatar = v.dir === 1 ? v.user_avatar : v.server_avatar
          return (
            <div className={myClassName} key={i}>
              <div className="avatar">
                <img
                  src={avatar}
                  alt=""
                />
              </div>
              <div className="content-box">
                <div className="message">{v.message}</div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        <input
          className="text"
          value={value}
          onChange={(e) => setValue(e.target.value)}
        ></input>
        <button className="send" onClick={() => handleSend()}>
          发送
        </button>
        <button onClick={() => handleChoose()}>媒体</button>
      </div>
    </div>
  );
};

export default App;
